package work.flow.demo.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.state.State;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import work.flow.demo.entity.test01.LightEvent;
import work.flow.demo.entity.test01.LightState;

import java.util.Map;

@RestController
public class Test01 {

    private static final Logger logger = LoggerFactory.getLogger(Test01.class);

    @Autowired
    private StateMachine<LightState, LightEvent> stateMachine;



    @GetMapping("/001")
    public String get01(@RequestParam Map<String, String> params) {
        // 确保状态机已启动
        if (!stateMachine.isComplete()) {
            stateMachine.start();
        }

        // 发送切换事件
        stateMachine.sendEvent(LightEvent.TOGGLE);

        // 安全获取当前状态
        return "当前灯泡状态: " + getCurrentState();

    }

    @GetMapping("/002")
    public String get02(@RequestParam Map<String, String> params) {
        // 获取当前状态
        LightState currentState = stateMachine.getState().getId();
        return "当前灯泡状态: " + currentState;
    }
    private String getCurrentState() {
        State<LightState, LightEvent> state = stateMachine.getState();
        if (state == null) {
            return "状态机未初始化";
        }
        return state.getId().toString();
    }

}
